﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using Lucene.Net;
using Lucene.Net.Index;
using Lucene.Net.Documents;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Analysis.Cn;
using Lucene.Net.Highlight;
using System.Text;


public partial class admin_search : System.Web.UI.Page
{
    //总记录数目
    int TotalCountRecord;
    //每页显示的条数
    int PageItem = 20;
    string strUrl = string.Empty;
    //当前页数
    int CurrentPage = 1;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["page"] != null)
        {
            if (!Int32.TryParse(Request.QueryString["page"].ToString(), out CurrentPage))
            {
                Response.Write("请输入数字分页参数。");
                Response.End();
                return;
            }
        }
        if (!this.IsPostBack)
        {
            this.BindData();
        }
    }
    public void BindData()
    {
        if (Request.QueryString["key"] != null)
        {
            string key = Request.QueryString["key"].ToString();
            strUrl = string.Format("&key={0}", key);
            if (key != string.Empty)
            {
                this.Rep_Resource.DataSource = GetTable(key, PageItem, CurrentPage, out TotalCountRecord);
                this.Rep_Resource.DataBind();
                BuildPagers();
                this.Pan_Page.Visible = true;

            }
            else
            {
                this.Pan_Page.Visible = false;
            }
        }
    }
    public DataTable GetTable(string key, Int32 pageSize, Int32 pageIndex, out int Total)
    {
        DataRow myrow;
        DataTable mytab = new DataTable();
        mytab.Columns.Add("ARTICLEID");
        mytab.Columns.Add("COLUMNID");
        mytab.Columns.Add("TITLE");
        mytab.Columns.Add("SUMMARY");
        mytab.Columns.Add("ADD_TIME");
        mytab.Clear();
        IndexReader reader = IndexReader.Open(Server.MapPath("admin/Index/"));
        IndexSearcher searcher = new IndexSearcher(reader);
        Lucene.Net.Analysis.Analyzer analyzer = new StandardAnalyzer();
        string query = this.Txt_Key.Text.Trim();
        Lucene.Net.Analysis.Analyzer highanalyzer = new StandardAnalyzer();
        MultiFieldQueryParser parser = new MultiFieldQueryParser(new string[] { "TITLE", "SUMMARY" }, highanalyzer);
        SimpleHTMLFormatter simpleHTMLFormatter = new SimpleHTMLFormatter("<span class=\"highlight\">", "</span>"); // 这是定义了在页面如何通过css来控制关键字的特征
        Query highquery = parser.Parse(key);
        Highlighter highlighter = new Highlighter(simpleHTMLFormatter, new QueryScorer(highquery));
        //Sort sort = new Sort(new SortField("id",SortField.FIELD_SCORE));
        Hits myhit = searcher.Search(highquery);
        highlighter.SetTextFragmenter(new SimpleFragmenter(100));
        Total = myhit.Length();
        for (int i = ((pageIndex - 1) * pageSize); i < (pageIndex * pageSize); i++)
        {
            if (i == Total)
            {
                break;
            }
            else
            {
                Lucene.Net.Documents.Document doc = myhit.Doc(i);
                string s_Title = doc.Get("TITLE");
                string s_Content = doc.Get("SUMMARY");
                Lucene.Net.Analysis.TokenStream TitlekenStream = highanalyzer.TokenStream("TITLE", new System.IO.StringReader(s_Title));
                Lucene.Net.Analysis.TokenStream ContentkeStream = highanalyzer.TokenStream("SUMMARY", new System.IO.StringReader(s_Content));
                string Title = highlighter.GetBestFragments(TitlekenStream, s_Title, 2, "...");
                string Content = highlighter.GetBestFragments(ContentkeStream, s_Content, 0, "..");

                myrow = mytab.NewRow();
                myrow[0] = doc.Get("ARTICLEID").ToString();
                myrow[1] = Title;
                myrow[2] = Content;
                myrow[3] = doc.Get("ADD_TIME").ToString();
                mytab.Rows.Add(myrow);
                searcher.Close();
                myrow.AcceptChanges();
            }


        }
        return mytab;
    }

    public void CreateIndex(string path)
    {
        SqlDataReader Dr = GetDR();
        IndexWriter writer = new IndexWriter(Server.MapPath(path), new ChineseAnalyzer(), true);
        writer.SetMergeFactor(20);  //      调整segment合并的频率和大小
        while (Dr.Read())
        {

            Document doc = GetDocumentObj(Dr["ARTICLEID"].ToString(), Dr["COLUMNID"].ToString(), Dr["TITLE"].ToString(), Dr["SUMMARY"].ToString(), Dr["ADD_TIME"].ToString());
            //    doc.SetBoost(1.5);
            //写入索引文档
            writer.AddDocument(doc);

        }
        Dr.Close();
        //优化文档
        writer.Optimize();
        //关闭
        writer.Close();
    }
    public SqlDataReader GetDR()
    {
        SqlConnection Conn = new SqlConnection("server=HUNTER\\HUNTER05;uid=sa;password=123@qwe;database=nestle;min pool size=4;min pool size=4;max pool size=100;packet size=3072");
        SqlCommand Cmd = new SqlCommand();
        Cmd.Connection = Conn;
        Conn.Open();
        Cmd.CommandText = string.Format("select top 5000 * from CMS_ARTICLE order by ADD_TIME asc");
        SqlDataReader Dr = Cmd.ExecuteReader(CommandBehavior.CloseConnection);
        return Dr;

    }
    public Document GetDocumentObj(string articleId,string columnid, string Title, string Content, string Add_Time)
    {
        Document doc = new Document();
        doc.Add(new Field("ARTICLEID", ID, Field.Store.YES, Field.Index.UN_TOKENIZED));
        doc.Add(new Field("COLUMNID", Title, Field.Store.YES, Field.Index.TOKENIZED));
        doc.Add(new Field("TITLE", Title, Field.Store.YES, Field.Index.TOKENIZED));
        doc.Add(new Field("SUMMARY", Content, Field.Store.YES, Field.Index.TOKENIZED));
        doc.Add(new Field("ADD_TIME", Add_Time, Field.Store.YES, Field.Index.UN_TOKENIZED));
        return doc;
    }
    public void BuildPagers()
    {
        //偏移量
        int Step = 10;
        int LeftNum = 0;
        int RightNum = 0;
        string PageUrl = Request.FilePath;
        int PageCount = (int)Math.Ceiling((double)(TotalCountRecord) / PageItem);
        if (CurrentPage - Step < 1)
        {
            LeftNum = 1;
        }
        else
        {
            LeftNum = CurrentPage - Step;
        }

        if (CurrentPage + Step > PageCount)
        {
            RightNum = PageCount;
        }
        else
        {
            RightNum = CurrentPage + Step;
        }
        StringBuilder OutPut = new StringBuilder();
        OutPut.Append("<li id='page_yema' style='float:left; padding-top:6px;'>");
        for (int i = LeftNum; i <= RightNum; i++)
        {
            if (i == CurrentPage)
            {
                OutPut.Append("<font style='margin-left:3px;' color=red>");
                OutPut.Append(i.ToString());
                OutPut.Append("</font>");
            }
            else
            {
                OutPut.Append("<a style='margin-left:3px;' href='");
                OutPut.Append(PageUrl);
                OutPut.Append("?page=");
                OutPut.Append(i.ToString());
                OutPut.Append(strUrl);
                OutPut.Append("'>");
                OutPut.Append(i.ToString());
                OutPut.Append("</a>");
            }
        }
        OutPut.Append("</li>");
        if (CurrentPage > 1)
        {
            OutPut.Insert(0, string.Format("<li style='float:left'><a href='{0}?page={1}{2}'><img src='../images/back_page_bt.gif' alt='上一页' width='50' height='20' border='0' style='margin-top:3px;'/></a></li>", PageUrl, (CurrentPage - 1), strUrl));
        }

        if (CurrentPage < PageCount)
        {
            OutPut.Append("<li style='float:left'><a href='");
            OutPut.Append(PageUrl);
            OutPut.Append("?page=");
            OutPut.Append(CurrentPage + 1);
            OutPut.Append(strUrl);
            OutPut.Append("'><img src='../images/next_page_bt.gif' alt='下一页' width='50px' height='20px' border='0' style='margin-top:3px;' /></a></li>");
        }
        this.PageInfo.Text = OutPut.ToString();
        this.left.Text = string.Format("总记录数:<font color='red'>{0}</font>  总页数:<font color='red'>{1}</font>", TotalCountRecord, PageCount);
    }

    protected void Btn_Create_Click(object sender, EventArgs e)
    {
        CreateIndex("admin/Index/");
    }

    protected void Btn_Search_Click(object sender, EventArgs e)
    {
        string key = this.Txt_Key.Text.Trim();
        if (key != null)
        {
            Response.Redirect(string.Format("search.aspx?key={0}", key));
        }
    }
}